package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.core.context.RootContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 拉起微信支付前，保存本地交易记录
     * 前提：订单跟充值支付状态都不能是已关闭
     *
     * @param paymentType 支付类型：1301-订单 1302-充值
     * @param orderNo     订单编号
     * @param userId      用户ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        //1.根据订单编号查询本地交易记录是否已存在，存在直接返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.构建本地交易记录对象 金额，内容都需要远程调用其他服务获取
        PaymentInfo paymentInfoDB = new PaymentInfo();
        //2.1 远程调用订单服务-根据订单编号查询订单信息得到订单中价格跟内容（订单状态不能是已关闭）
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.1.1 远程调用订单服务获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在，订单编号：{}！", orderNo);
            //2.1.2 判断订单状态非关闭
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(400, "订单状态有误无法继续支付！");
            }
            //2.1.3 为本地交易记录中金额，内容赋值
            paymentInfoDB.setAmount(orderInfo.getOrderAmount());
            paymentInfoDB.setContent("订单：" + orderInfo.getOrderDetailList().get(0).getItemName());
        }
        //2.2 远程调用账户服务-根据订单编号查询充值信息得到价格跟内容（充值状态不能是已关闭）
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.2.1 远程调用账户服务获取充值记录
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录为空,订单编号：{}", orderNo);
            //2.2.2 判断充值记录状态
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())) {
                throw new GuiguException(400, "充值订单状态有误无法继续支付！");
            }
            //2.2.3 为本地交易记录中金额跟内容赋值
            paymentInfoDB.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfoDB.setContent("充值：" + rechargeInfo.getRechargeAmount());
        }

        //2.3 为其他本地交易记录中属性赋值
        //2.3.1 设置交易用户ID
        paymentInfoDB.setUserId(userId);
        //2.3.2 设置交易类型
        paymentInfoDB.setPaymentType(paymentType);
        //2.3.3 设置订单编号
        paymentInfoDB.setOrderNo(orderNo);
        //2.3.3 设置付款方式 TODO 暂时仅支持微信
        paymentInfoDB.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //2.3.4 设置本地交易记录状态
        paymentInfoDB.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //3.保存本地交易记录
        paymentInfoMapper.insert(paymentInfoDB);
        return paymentInfoDB;
    }

    /**
     * 用户付款成功后，修改本地交易记录
     *
     * @param transaction 微信交易对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentInfoSuccess(Transaction transaction) {
        //1.根据订单编号查询本地交易记录状态
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(queryWrapper);
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
            //如果已支付：返回即可
            return;
        }
        //2.修改本地交易记录
        //2.1 本地交易记录关联微信支付交易ID
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        //2.2 更新回调时间，及回调内容
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        //2.3 将本地交易支付状态：已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfoMapper.updateById(paymentInfo);

        //3.todo 远程调用订单服务/账户服务 完成订单/充值状态变更：已支付
        //3.1 判断支付类型：1301-订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
            Result result = orderFeignClient.orderPaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改订单状态异常：" + orderNo);
            }
        }

        //3.2 TODO 判断支付类型：1302-充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改余额异常：" + orderNo);
            }

            String xid = RootContext.getXID(); //
        }
    }
}
